<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2017/6/13
 * Time: 上午11:50
 */

namespace app\src\seller\logic;


use app\src\account\enmu\AccountEnmu;
use app\src\base\helper\ExceptionHelper;
use app\src\base\helper\PageHelper;
use app\src\base\logic\BaseLogic;
use app\src\invite\logic\InviteCodeLogic;
use app\src\platform\logic\PlatformLogic;
use app\src\seller\emnu\SellerOrderStatusEmnu;
use app\src\user\enum\RoleEnum;
use app\src\userRoles\logic\UserRolesLogic;
use think\Db;
use think\exception\DbException;

class SellerLogic extends BaseLogic
{

    /**
     * 添加商家
     * @param $entity
     */
    public function addSeller($entity)
    {
        $data = [
            'uid' => $entity['uid'],
            'waiter_id' => isset($entity['waiter_id']) ? $entity['waiter_id'] : 0,
            'name' => $entity['name'],
            'grade' => isset($entity['grade']) ? $entity['grade'] : 0,
            'price' => isset($entity['price']) ? $entity['price'] : 0,
            'position' => $entity['position'],
            'lng' => $entity['lng'],
            'lat' => $entity['lat'],
            'parent_id' => $entity['parent_id'],
            'logo' => isset($entity['logo']) ? $entity['logo'] : 0,
            'main_img' => isset($entity['main_img']) ? $entity['main_img'] : 0,
            'main_img_small' => isset($entity['main_img_small']) ? $entity['main_img_small'] : 0,
            'contact_number' => isset($entity['contact_number']) ? $entity['contact_number'] : 0,
            'synopsis' => $entity['synopsis'],
            'scope' => $entity['scope'],
            'first_offer' => $entity['first_offer'], //首次优惠政策5元 10元,
            'first_offer_num' => isset($entity['first_offer_num']) ? $entity['first_offer_num'] : 0,
            'discount_rate' => $entity['discount_rate'],
            'rack_back_rate' => $entity['rack_back_rate'],
            'bank_card_name' => isset($entity['bank_card_name']) ? $entity['bank_card_name'] : '',
            'bank_card_no' => isset($entity['bank_card_no']) ? $entity['bank_card_no'] : '',
            'status' => 0,
            'category_id' => isset($entity['category_id']) ? $entity['category_id'] : '',
            'category_level' => isset($entity['category_level']) ? $entity['category_level'] : '',
        ];

        $result = $this->add($data);
        if($result['status']){
            $seller_id = $result['info'];

            //添加用户角色
            (new UserRolesLogic)->addRole($entity['uid'], RoleEnum::ROLE_Seller, $seller_id);
            if(isset($entity['waiter_id']) && $entity['waiter_id']!=0){
                (new UserRolesLogic)->addRole($entity['waiter_id'], RoleEnum::ROLE_Waiter, $seller_id);
            }

            //添加邀请码
            (new InviteCodeLogic)->create(AccountEnmu::SELLER, $seller_id);

            return $this->apiReturnSuc($seller_id);
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 更新商家信息
     * @param $seller_id
     * @param $entity
     * @return array
     */
    public function updateSeller($seller_id, $entity)
    {
        if($this->checkSeller($seller_id)!==true) return $this->apiReturnErr('error seller');
        $result = $this->save(['id' => $seller_id], $entity);
        if($result['status']){
            return $this->apiReturnSuc('success');
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 设置店小二
     * @param $seller_id
     * @param $waiter_id
     * @return array
     */
    public function setWaiter($seller_id, $waiter_id)
    {

        //判断是否已经是其他店的店小二
        $map = [
            'status' => 0,
            'waiter_id' => $waiter_id,
            'id' => ['<>', $seller_id]
        ];
        $result = $this->count($map);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if($result['info'] > 0) return $this->apiReturnErr('该用户已经是其他店的店小二了,无法设置');

        //移除旧的店小二的角色
        $result = $this->getSellerInfo($seller_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if($result['info']['waiter_id']!=0){
            $result = (new UserRolesLogic)->removeRole($result['info']['waiter_id'], RoleEnum::ROLE_Waiter, $seller_id);
            if(!$result) return $this->apiReturnErr('设置店小二失败');
        }
        $result = (new UserRolesLogic)->addRole($waiter_id, RoleEnum::ROLE_Waiter, $seller_id);
        if($result){
            return $this->updateSeller($seller_id, ['waiter_id' => $waiter_id]);
        }else{
            return $this->apiReturnErr('设置店小二失败');
        }
    }

    /**
     * 移除店小二
     * @param $seller_id
     */
    public function removeWaiter($seller_id, $waiter_id)
    {
        $result = (new UserRolesLogic)->removeRole($waiter_id, RoleEnum::ROLE_Waiter, $seller_id);
        if($result){
            return $this->updateSeller($seller_id, ['waiter_id' => 0]);
        }else{
            return $this->apiReturnErr('移除店小二失败');
        }
    }

    /**
     * 移动商家到另一个个人创业平台
     * @param $seller_id
     * @param $platform_id
     */
    public function moveSeller($seller_id, $platform_id)
    {
        if($this->checkSeller($seller_id)!==true){
            return $this->apiReturnErr('error seller');
        }
        if((new PlatformLogic)->checkPlatform($platform_id)!==true){
            return $this->apiReturnErr('error platform_id');
        }
        $entity = [
            'parent_id' => $platform_id
        ];
        $result = $this->saveByID($seller_id, $entity);
        if($result['status']){
            return $this->apiReturnSuc('success');
        }else{
            return $this->apiReturnErr($result['info']);
        }

    }

    public function deleteSeller($seller_id)
    {
        $result = $this->getSellerInfo($seller_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);

        $seller_info = $result['info'];

        Db::startTrans();

        try{
            $map = [
                'id' => $seller_id
            ];

            $result = $this->pretendDelete($map);
            if(!$result['status']){
                Db::rollback();
                return $this->apiReturnErr($result['info']);
            }

            //移除店小二角色
            $result = (new UserRolesLogic)->removeRole($seller_info['uid'], RoleEnum::ROLE_Seller, $seller_id);
            if(!$result){
                Db::rollback();
                return $this->apiReturnErr($result['info']);
            }

            //移除商家角色
            $result = (new UserRolesLogic)->removeRole($seller_info['waiter_id'], RoleEnum::ROLE_Waiter, $seller_id);
            if(!$result){
                Db::rollback();
                return $this->apiReturnErr($result['info']);
            }

            Db::commit();

            return $this->apiReturnSuc('success');

        }catch (DbException $ex){
            Db::rollback();
            return $this->apiReturnErr(ExceptionHelper::getErrorString($ex));
        }
    }

    /**
     * 判断该商家是否正常（未被删除）
     */
    public function checkSeller($seller_id)
    {
        $map = [
            'id' => $seller_id,
            'status' => 0
        ];

        $result = $this->getInfo($map);
        if(!$result['status']) return $result['info'];
        if(!empty($result['info'])){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取正常状态商家
     * @param $seller_id
     */
    public function getSellerInfo($seller_id)
    {
        $map = [
            'id' => $seller_id,
            'status' => 0
        ];

        $result = $this->getInfo($map);
        return $result;
    }

    /**
     * 查询附近商家
     * @param $lng
     * @param $lat
     * @param bool $maxDistance 距离（单位米）
     * @param bool $name
     * @param bool $city_code
     * @param PageHelper $pageHelper
     * @param string $cate_id
     * @return array
     */
    public function getNearby($lng, $lat, $maxDistance = false, $name = false, $city_code = false, PageHelper $pageHelper,$cate_id = false)
    {
        $model = $this->getModel();
        try{
            $where = "`itboye_seller`.status = 0";
            if($maxDistance){
                $where .= " AND getDistance($lng,$lat,lng,lat) <= $maxDistance";
            }

            $join = '';
            if($city_code){
                $join = "JOIN `itboye_platform` ON `itboye_seller`.parent_id = `itboye_platform`.id ";
                $where .= " AND `itboye_platform`.city_code = $city_code";
            }

            if($name){
                $where .= " AND `itboye_seller`.name LIKE '%$name%'";
            }

            if($cate_id){
                $where .= " AND `itboye_seller`.category_id =$cate_id";
            }

            $sql = "SELECT `itboye_seller`.*, getDistance($lng,$lat,lng,lat) AS distance  FROM `itboye_seller` $join WHERE $where ORDER BY distance LIMIT {$pageHelper->getOffset()},{$pageHelper->getPageSize()}";
            $count_sql = "SELECT count(*) AS tp_count FROM (SELECT getDistance($lng,$lat,lng,lat) AS distance  FROM `itboye_seller` $join WHERE $where) AS d";
            $list = $model->query($sql);
            if (false === $list) return $this -> apiReturnErr($model -> getError());
            $result = $model->query($count_sql);
            $count = $result[0]['tp_count'];

            foreach ($list as &$val){
                //获取月销量
                $result = $this->get_monthly_sales($val['id']);
                if(!$result['status']) return $this->apiReturnErr($result['info']);
                $val['monthly_sales'] = $result['info'];
            }

            return $this -> apiReturnSuc(["count" => $count, "list" => $list]);
        }catch (DbException $ex){
            return $this -> apiReturnErr(ExceptionHelper::getErrorString($ex));
        }
    }

    /**
     * 商家详情
     * @param $seller_id
     * @return array
     */
    public function detailInfo($seller_id)
    {
        $map = ['id' => $seller_id, 'status' => 0];
        $result = $this->getInfo($map);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if(empty($result['info'])) return $this->apiReturnErr('error seller');
        $seller_info = $result['info'];

        //获取月销量
        $result = $this->get_monthly_sales($seller_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        $seller_info['monthly_sales'] = $result['info'];

        //查询店铺优惠
        $map = ['seller_id' => $seller_id, 'status' => 0, 'begin_time' => ['<', NOW_TIME], 'end_time' => ['>=', NOW_TIME]];
        $order = 'id desc';
        $result = (new SellerPromotionLogic)->queryNoPaging($map,$order);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        $promotion = $result['info'];

        return $this->apiReturnSuc(['seller' => $seller_info, 'promotion' => $promotion]);
    }


    /**
     * 获取月销量
     * @param $seller_id
     * @return array
     */
    public function get_monthly_sales($seller_id)
    {
        //月销售 查询订单表
        $begin_time = strtotime('midnight first day of this month');
        $end_time = strtotime('midnight first day of next month');
        $map = [
            'seller_id' => $seller_id,
            'status' => 0,
            'order_status' => 1, //已支付,
            'create_time' => [['>=',$begin_time], ['<',$end_time]]
        ];
        $result = (new SellerOrderLogic)->count($map);
        return $result;
    }

    public function childAll($platform_id)
    {
        if((new PlatformLogic)->checkPlatform($platform_id)!==true) return $this->apiReturnErr('error platform');
        $map = [
            'parent_id' => $platform_id,
            'status' => 0
        ];
        $result = $this->queryNoPaging($map);
        return $result;
    }

    public function childAll2($map)
    {
        $result = $this->queryNoPaging($map);
        return $result;
    }


    /*
     * 购买时信息查询
     */
    public function checkBuy($seller_id,$uid){
        $map['uid'] = $uid;
        $array_status = SellerOrderStatusEmnu::PAY;
        $map['order_status'] = ['in',$array_status];
        $result = (new SellerOrderLogic())->count($map);
        $seller = $this->getInfo(['id'=>$seller_id,'status'=>0],'','id,name,main_img,first_offer,first_offer_num,lock_first_offer');

        if($result['status']&&$seller['status']){
            if(empty($seller['info'])) return $this->apiReturnErr('找不到商家');
            if($result['info']>0||$seller['info']['first_offer_num']<=0||$seller['info']['lock_first_offer']==1){
                //不是第一购买 或该商家已经用完优惠
                $seller['info']['is_first'] = 0;
            }else{
                //第一次购买
                $seller['info']['is_first'] = 1;
            }

            return $this->apiReturnSuc($seller['info']);
        }else{
            return $this->apiReturnErr('查询出错');
        }
    }

    /**
     * 商家订单统计
     * @param $map
     * @param array $page
     * @param bool $order
     * @return array
     */
    public function querySellerOrderSum($map = null, $page = ['curpage'=>1, 'size'=>10], $order = false)
    {

        try{
            $query = (new SellerOrderLogic)->getModel();
            if(!empty($map)) $query = $query->where($map);
            if(false !== $order) $query = $query->order($order);
            $query = $query->alias('so')->where($map)->field('so.seller_id,count(so.id) as order_count,sum(so.amount) as sum_amount,sum(so.no_discount) as sum_no_discount,sum(so.price) as sum_price,sum(so.income) as sum_income,s.name,s.contact_number,first_offer')
                ->join('__SELLER__ s','so.seller_id = s.id')
                ->where('s.status = 0')
                ->group('seller_id');

            $start = max(0,(intval($page['curpage'])-1)*intval($page['size']));
            $list = $query -> limit($start,$page['size']) -> select();

            $count = (new SellerOrderLogic)->getModel()->alias('so') ->join('__SELLER__ s','so.seller_id = s.id')
                ->where('s.status = 0')
                ->field('so.seller_id,count(so.id) as order_count,sum(so.amount) as sum_amount,sum(so.no_discount) as sum_no_discount,sum(so.price) as sum_price,sum(so.income) as sum_income,s.name,s.contact_number,first_offer')
                ->where($map) ->group('seller_id') -> count();
            $data = [];
            foreach ($list as $vo){
                if(method_exists($vo,"toArray")){
                    array_push($data,$vo->toArray());
                }
            }
            return $this -> apiReturnSuc(["count" => $count, "list" => $data]);
        }catch (DbException $ex){
            return $this -> apiReturnErr(ExceptionHelper::getErrorString($ex));
        }

    }

    /**
     * 商家订单列表
     * @param null $map
     * @param array $page
     * @param bool $order
     * @return array
     */
    public function querySellerOrder($map = null, $page = ['curpage'=>1, 'size'=>10], $order = false)
    {
        try{
            $query = (new SellerOrderLogic)->getModel();
            if(!empty($map)) $query = $query->where($map);
            if(false !== $order) $query = $query->order($order);
            $query = $query->alias('so')->where($map)->field('u.nickname,u.mobile,so.amount,so.price,so.no_discount,so.id,so.income,so.create_time,so.is_first,p.type')
                ->join('__SELLER__ s','so.seller_id = s.id')
                ->join(['v_user_info' => 'u'],'so.uid = u.id','LEFT')
                ->join('__PAYMENT__ p','so.order_code = p.order_code','LEFT')
                ->where('s.status = 0');

            $start = max(0,(intval($page['curpage'])-1)*intval($page['size']));
            $list = $query -> limit($start,$page['size']) -> select();

            $count = (new SellerOrderLogic)->getModel()->alias('so')
                ->join('__UCENTER_MEMBER__ um','so.uid = um.id')
                ->join('__SELLER__ s','so.seller_id = s.id')
                ->where('s.status = 0')
                ->where($map) -> count();
            $data = [];
            foreach ($list as $vo){
                if(method_exists($vo,"toArray")){
                    array_push($data,$vo->toArray());
                }
            }
            return $this -> apiReturnSuc(["count" => $count, "list" => $data]);
        }catch (DbException $ex){
            return $this -> apiReturnErr(ExceptionHelper::getErrorString($ex));
        }
    }



}